//
//  DetailsViewController.m
//  项目
//
//  Created by 焦钟培 on 15-1-4.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DetailsViewController.h"
#import "ReadingRoomModel.h"
#import "ConnectModel.h"
#import "DetailBace.h"
#import "DetailModel.h"
#import <ShareSDK/ShareSDK.h>
#import "DengLuViewController.h"
#import "Masonry.h"
#import "WebColor.h"
#import "Reachability.h"


#define kBlueColor [UIColor colorWithRed:129/255.0 green: 198/255.0 blue: 221/255.0 alpha: 1.0]

#define DEFAULTS ([NSUserDefaults standardUserDefaults])

@interface DetailsViewController ()<UIWebViewDelegate>

@end

@implementation DetailsViewController
- (void)dealloc
{
    [_tiButton release];
    [_iamg release];
    [_path release];
    [_modelArray release];
    [_arrays release];
    [_plotArray release];
    [_parameter release];
    [_webView release];
    [_right release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.parameter = [[ReadingRoomModel alloc] init];
        [_parameter release];
        self.plotArray = [NSMutableArray array];
        self.arrays = [NSMutableArray array];
        self.modelArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.iamg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shua.png"]];
    _iamg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    [self.view addSubview:_iamg];
    
    self.tiButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _tiButton.frame = CGRectMake(0, 0, 0, 0);
    _tiButton.backgroundColor = [UIColor grayColor];
    [_tiButton setTitle:@"网络异常请重试" forState:UIControlStateNormal];
    [_tiButton setTitleColor:[UIColor lightTextColor] forState:UIControlStateNormal];
    _tiButton.layer.cornerRadius = 10;
    [_tiButton addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_tiButton];
    [self startI];
    
    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.RepeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [_iamg.layer addAnimation:rotationAnimation forKey:@"rotation"];
    // Do any additional setup after loading the view.
}
- (BOOL)judgeConnected
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    NetworkStatus status = [reach currentReachabilityStatus];
    switch (status) {
        case NotReachable:
        {
            return NO;
        }
            break;
        case ReachableViaWiFi:
        {
            return YES;
        }
            break;
        case ReachableViaWWAN:
        {
            return YES;
        }
            break;
        default:
            break;
    }
}


#warning 解析
- (void)startI
{
    BOOL judge = [self judgeConnected];
    if (!judge) {
        [_iamg removeFromSuperview];
        _tiButton.frame = CGRectMake(80, self.view.frame.size.height/2 - 30, self.view.frame.size.width - 160, 60);
        return;
    }
    NSDictionary *dic1 = [NSDictionary dictionaryWithObject:_parameter.os forKey:@"os"];
    NSDictionary *dic2 = [NSDictionary dictionaryWithObject:_parameter.ver forKey:@"ver"];
    NSDictionary *dic3 = [NSDictionary dictionaryWithObject:_parameter.op forKey:@"op"];
    NSDictionary *dic4 = [NSDictionary dictionaryWithObject:_parameter.cid forKey:@"cid"];
    NSDictionary *dic5 = [NSDictionary dictionaryWithObject:_parameter.aid forKey:@"aid"];
    NSDictionary *dic6 = [NSDictionary dictionaryWithObject:_parameter.p forKey:@"p"];
    NSDictionary * dic7 = [NSDictionary dictionaryWithObject:_parameter.w forKey:@"w"];
    NSDictionary *dic8 =[NSDictionary dictionaryWithObject:_parameter.cFrom forKey:@"cFrom"];
    NSMutableArray *arrays = [NSMutableArray arrayWithObjects:dic1,dic2,dic3,dic4,dic5,dic6,dic7,dic8, nil];
    [_arrays addObjectsFromArray:arrays];
    
    [ConnectModel connectModelWithUrlStr:@"http://mobi.360doc.com/v17/ajax/article.ashx" parmaters:arrays block:^(NSData *data) {
        [_iamg removeFromSuperview];
        NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
        NSString *str = [result stringByReplacingOccurrencesOfString:@"({" withString:@"{"];
        NSString *strs = [str stringByReplacingOccurrencesOfString:@"})" withString:@"}"];
        NSData *newData = [strs dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary * dics = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dicFirst = [dics objectForKey:@"aCnt"];
        NSString * path = [dicFirst objectForKey:@"Cnt"];
        NSString *path1 = [path stringByReplacingOccurrencesOfString:@"src=\"imgloading.png\" onclick=\"showBigImage(" withString:@"src="];
        NSDictionary *second = [dics objectForKey:@"aInf"];
        [_modelArray addObject:[second objectForKey:@"SaverUserid"]];
        [_modelArray addObject:[second objectForKey:@"Tit"]];
        self.path = [NSString stringWithFormat:@"%@\n%@",[second objectForKey:@"Tit"],[second objectForKey:@"FromUrl"]];
        
#warning 创建webView
        self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height - 70)];
        [_webView setBackgroundColor:[UIColor whiteColor]];
        _webView.scrollView.contentSize = CGSizeMake(_webView.scrollView.contentSize.width, _webView.scrollView.contentSize.height + 80);
        
        _webView.scalesPageToFit = NO;
        [_webView loadHTMLString:path1 baseURL:nil];
        
        [self.view addSubview:_webView];
        [_webView release];
        for (UIView *subView in _webView.scrollView.subviews) {
            subView.frame = CGRectMake(subView.frame.origin.x, subView.frame.origin.y + 90, subView.frame.size.width, subView.frame.size.height);
        }
        
        
#warning Tit
        UILabel *titLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, _webView.frame.size.width, 44)];
        titLabel.text = [second objectForKey:@"Tit"];
        titLabel.numberOfLines = 0;
        titLabel.font = [UIFont systemFontOfSize:20];
        titLabel.adjustsFontSizeToFitWidth = YES;
        [_webView.scrollView addSubview:titLabel];
        [titLabel release];
        
#warning SUH
        UIImageView *SUHimage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 49, 36, 36)];
        SUHimage.layer.masksToBounds = YES;
        SUHimage.layer.cornerRadius = 18;
        NSURL *SUHurl = [NSURL URLWithString:[second objectForKey:@"SUH"]];
        NSData *SUHdata = [NSData dataWithContentsOfURL:SUHurl];
        SUHimage.image = [UIImage imageWithData:SUHdata];
        [_webView.scrollView addSubview:SUHimage];
        [SUHimage release];
        
#warning SNName
        UILabel *SNNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 49, _webView.frame.size.width - 50, 18)];
        SNNameLabel.text = [second objectForKey:@"SNName"];
        SNNameLabel.textColor = [UIColor grayColor];
        SNNameLabel.font = [UIFont systemFontOfSize:14];
        [_webView.scrollView addSubview:SNNameLabel];
        [SNNameLabel release];
        
#warning SD
        UILabel *SDLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 67, _webView.frame.size.width - 50, 18)];
        SDLabel.text = [second objectForKey:@"SD"];
        SDLabel.textColor = [UIColor grayColor];
        SDLabel.font = [UIFont systemFontOfSize:14];
        [_webView.scrollView addSubview:SDLabel];
        [SDLabel release];
        
        UIView *views = [[UIView alloc] init];
        views.tag = 10;
        views.backgroundColor = kBlueColor;
        [self.view addSubview:views];
        [views mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(0);
            make.top.equalTo(self.view.mas_top).offset(20);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 44));
        }];
        
        
        UIButton *left = [[UIButton alloc] init];
        [left setBackgroundImage:[UIImage imageNamed:@"fanhui.png"] forState:UIControlStateNormal];
        [left addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
        [views addSubview:left];
        [left mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(self.view.mas_left).offset(6);
           make.top.equalTo(self.view.mas_top).offset(27);
           make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width / 10, 30));
        }];
        
        [left release];
        
        
        UIButton *center = [[UIButton alloc] init];
        [center setBackgroundImage:[UIImage imageNamed:@"fenxiang.png"] forState:UIControlStateNormal];
        [center addTarget:self action:@selector(centerAction) forControlEvents:UIControlEventTouchUpInside];
        [views addSubview:center];
        [center mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(left.mas_right).offset(6 + self.view.frame.size.width / 6);
            make.top.equalTo(self.view.mas_top).offset(27);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width / 10, 30));
        }];
        [center release];
        
        
        UIButton *rRight = [[UIButton alloc] init];
        [rRight setBackgroundImage:[UIImage imageNamed:@"wenzi.png"] forState:UIControlStateNormal];
        [rRight addTarget:self action:@selector(RrightAction) forControlEvents:UIControlEventTouchUpInside];
        [views addSubview:rRight];
        [rRight mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(center.mas_right).offset(6 + self.view.frame.size.width / 6);
            make.top.equalTo(self.view.mas_top).offset(27);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width / 10, 30));
        }];
        [rRight release];
        
        
        self.right = [[UIButton alloc] init];
        [_right setBackgroundImage:[UIImage imageNamed:@"shoucang1.png"] forState:UIControlStateNormal];
        [_right addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
        [views addSubview:_right];
        [_right mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(rRight.mas_right).offset(6 + self.view.frame.size.width / 6);
            make.top.equalTo(self.view.mas_top).offset(27);
            make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width / 10, 30));
        }];
        [_right release];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSInteger nid = [[user objectForKey:@"nid"] integerValue];
        DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
        NSArray *array = [model.detail_tit componentsSeparatedByString:@"$$"];
        for (NSString *histroy in array) {
            if ([histroy isEqualToString:[_modelArray lastObject]]) {
                [_right setBackgroundImage:[UIImage imageNamed:@"shoucang2.png"] forState:UIControlStateNormal];
            }
        }
        
        
        UIButton *bigger = [[UIButton alloc] initWithFrame:CGRectMake(-self.view.frame.size.width / 4, 80, self.view.frame.size.width / 4 - 20, 40)];
        [bigger setImage:[UIImage imageNamed:@"fangda1.png"] forState:UIControlStateNormal];
        bigger.layer.cornerRadius = 5;
        bigger.clipsToBounds = YES;
        bigger.tag = 1;
        [bigger setBackgroundImage:[UIImage imageNamed:@"lantian10.png"] forState:UIControlStateNormal];
        [bigger addTarget:self action:@selector(biggerButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:bigger];
        [bigger release];
        
        UIButton *smaller = [[UIButton alloc] initWithFrame:CGRectMake(-self.view.frame.size.width / 4, 80, self.view.frame.size.width / 4 - 20, 40)];
        smaller.backgroundColor = [WebColor hotPink];
        [smaller setImage:[UIImage imageNamed:@"wenzi1.png"] forState:UIControlStateNormal];
        [smaller setBackgroundImage:[UIImage imageNamed:@"lantian10.png"] forState:UIControlStateNormal];
        smaller.layer.cornerRadius = 5;
        smaller.clipsToBounds = YES;
        smaller.tag = 2;
        [smaller addTarget:self action:@selector(smallerButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:smaller];
        [smaller release];
        [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(currI) userInfo:nil repeats:NO];
    }];


}


- (void)leftAction
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

#warning 分享
- (void)centerAction
{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *str = [user objectForKey:@"login"];
    
    if ([str isEqualToString:@"yes"]) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"haiyang" ofType:@"jpg"];
        id<ISSContent> publishContent = [ShareSDK content:_path
                                           defaultContent:@"测试一下" image:[ShareSDK imageWithPath:imagePath]title:@"ShareSDK"
                                                      url:@"http://www.mob.com" description:@"这是一条测试信息"
                                                mediaType:SSPublishContentMediaTypeNews];
        //创建弹出菜单容器
        
        id<ISSContainer> container = [ShareSDK container];
        
        id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:@"内容分型" oneKeyShareList:[NSArray defaultOneKeyShareList] qqButtonHidden:YES wxSessionButtonHidden:YES wxTimelineButtonHidden:YES showKeyboardOnAppear:YES shareViewDelegate:self friendsViewDelegate:self picViewerViewDelegate:nil];
        
        
        
        //弹出分享菜单
        [ShareSDK showShareActionSheet:container
                             shareList:nil
                               content:publishContent
                         statusBarTips:YES
                           authOptions:nil
                          shareOptions:shareOptions
                                result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                    
                                    if (state == SSResponseStateSuccess)
                                    {
                                        NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                    }
                                    else if (state == SSResponseStateFail)
                                    {
                                        NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                    }
                                }];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不好意思" message:@"请您先登陆" delegate:self cancelButtonTitle:@"登陆" otherButtonTitles:@"取消", nil];
        
        [alert show];
        [alert release];
    }
    
}





#warning 文字设置点击

- (void)RrightAction
{
    if (!_judge) {
        if (_buttonTag == 0) {
            _buttonTag = 2;
        }
        UIButton *button = (UIButton *)[self.view viewWithTag:_buttonTag];

        [UIView animateWithDuration:0.25 * _buttonTag animations:^{
            button.frame = CGRectMake(self.view.frame.size.width/2 * (_buttonTag - 1) + 50, 80, self.view.frame.size.width/4 - 20, 40);
            _buttonTag--;
            if (_buttonTag != 0) {
                [NSTimer scheduledTimerWithTimeInterval:0.25f target:self selector:@selector(RrightAction) userInfo:nil repeats:NO];
            }else{
                _judge = YES;
            }
                
        }];
    }else{
        [self releaseButton];
        _buttonTag = 0;
    }
}

- (void)biggerButton
{
    
    int numOfFont = [[DEFAULTS objectForKey:@"numOfFont"] intValue];
    if (numOfFont < 250) {
        numOfFont += 20;
        NSString * str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", numOfFont];
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        NSString * font = [NSString stringWithFormat:@"%d", numOfFont];
        [DEFAULTS setObject:font forKey:@"numOfFont"];
    }

}
- (void)currI
{
    int numOfFont = [[DEFAULTS objectForKey:@"numOfFont"] intValue];
    NSString * strings = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",numOfFont];
    [self.webView stringByEvaluatingJavaScriptFromString:strings];
    NSString * font = [NSString stringWithFormat:@"%d", numOfFont];
    [DEFAULTS setObject:font forKey:@"numOfFont"];
    [DEFAULTS setObject:font forKey:@"numOfFont"];
}
- (void)smallerButton
{
    int numOfFont = [[DEFAULTS objectForKey:@"numOfFont"] intValue];
    if (numOfFont > 60) {
        numOfFont -=20;
        NSString * str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", numOfFont];
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        NSString * font = [NSString stringWithFormat:@"%d", numOfFont];
        [DEFAULTS setObject:font forKey:@"numOfFont"];
    }

}


- (void)releaseButton
{
    _judge = NO;
    for (int i = 1; i < 5; i++) {
        UIButton *button = (UIButton *)[self.view viewWithTag:i];
        button.frame = CGRectMake(-self.view.frame.size.width/4, 80, self.view.frame.size.width/4 - 20, 40);
    }
}



#warning 收藏点击

- (void)rightAction
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSInteger nid = [[user objectForKey:@"nid"] integerValue];
    NSString *str = [user objectForKey:@"login"];
    if ([str isEqualToString:@"yes"]) {
    NSString *str1 = [ConnectModel connectWithUrlStr:@"http://mobi.360doc.com/v17/ajax/article.ashx" parmaters:_arrays];
   NSString *show = @"";
        DetailModel *model = [[DetailBace searchDetail:nid] firstObject];
        if (model.detail_tit.length == 0) {
            show = [NSString stringWithFormat:@"收藏成功"];
            [DetailBace updateDetail_tit:[_modelArray lastObject] detail_id:nid detail_http:str1];
        }else{
            NSArray *array = [model.detail_tit componentsSeparatedByString:@"$$"];
            for (int i = 0; i < [array count]; i++) {
                NSString *tit = [array objectAtIndex:i];
                if ([tit isEqualToString:[_modelArray lastObject]]) {
                    show = [NSString stringWithFormat:@"已收藏"];
                    break;
                }else if (i == [array count]-1){
                   show = [NSString stringWithFormat:@"收藏成功"];
                    [DetailBace updateDetail_tit:[NSString stringWithFormat:@"%@$$%@",[_modelArray lastObject],model.detail_tit] detail_id:nid detail_http:[NSString stringWithFormat:@"%@$$%@",str1,model.detail_http]];
                }
            }
        }
        
    self.alert = [[UIAlertView alloc] initWithTitle:@"提示" message:show delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];
    
    [_right setBackgroundImage:[UIImage imageNamed:@"shoucang2.png"] forState:UIControlStateNormal];
    [_alert show];
    [_alert release];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Rinse" object:self userInfo:nil];
        
    } else {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"不好意思" message:@"请您先登陆" delegate:self cancelButtonTitle:@"登陆" otherButtonTitles:@"取消", nil];
        
        [alert1 show];
        [alert1 release];
    
    }
}

- (void)timerAction:(id)sender
{
    
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
}


#warning 给Alert按钮(UIAlertViewDelegate协议)

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        DengLuViewController *dengController = [[DengLuViewController alloc] init];
        [self presentViewController:dengController animated:YES completion:nil];
        dengController.view.frame = CGRectMake(0, 0, dengController.view.frame.size.width, 0);
        [dengController release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
